package vip.ola.pay.channel.daifuchannel.newbaolong;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import vip.ola.core.common.util.IPUtility;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.PayDigestUtil;
import vip.ola.core.common.util.PayUtil;
import vip.ola.core.entity.AgentpayPassageAccount;
import vip.ola.core.entity.TransOrder;
import vip.ola.pay.batchpay.PaysUtil;
import vip.ola.pay.batchpay.RSAUtils;
import vip.ola.pay.ctrl.common.BaseController;
import vip.ola.pay.mq.BaseNotify4MchTrans;
import vip.ola.pay.service.RpcCommonService;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import static vip.ola.core.common.constant.PayConstant.TRANS_STATUS_COMPLETE;
import static vip.ola.core.common.constant.PayConstant.TRANS_STATUS_SUCCESS;

@RequestMapping("/api/newblong")
@Controller
public class NewblongTransController extends BaseController {

    private static final MyLog _log = MyLog.getLog(NewblongTransController.class);

    @Autowired
    private RpcCommonService rpcCommonService;

    @Autowired
    public BaseNotify4MchTrans baseNotify4MchTrans;

    @PostMapping("/notify")
    @ResponseBody
    public String notify(@RequestBody JSONObject object, HttpServletRequest request){
        _log.info("接收NewblongTransController回调：" + object);
        // 判断请求IP是否允许+"："
        String clintIp = IPUtility.getClientIp(request);
        _log.info("请求ip为：" + clintIp);
        boolean isAllow = PayUtil.ipAllow(clintIp, "180.76.37.236", "");
        if (!isAllow) {
            _log.info( "IP[" + clintIp + "]不允许访问");
            return "ip fail";
        }
        String transOrderId = object.getString("merReqNo");
        TransOrder payOrder = rpcCommonService.rpcTransOrderService.findByTransOrderId(transOrderId);
        BigDecimal orderMoney = BigDecimal.valueOf(Double.valueOf(object.getString("amt")));
        if (orderMoney.longValue() != payOrder.getAmount()){
            return "money fail";
        }
        if(payOrder == null){
            return "order not exist!";
        }
        if (payOrder.getStatus() == TRANS_STATUS_SUCCESS || payOrder.getStatus() == TRANS_STATUS_COMPLETE) {
            return "success";
        }
        AgentpayPassageAccount payPassageAccount = rpcCommonService.rpcAgentpayPassageAccountService.findById(payOrder.getPassageAccountId());
        if(payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())){
            return "fail";
        }
        JSONObject accountParams = JSONObject.parseObject(payPassageAccount.getParam());
        String retSign = object.getString("sign");
        String privateKey = accountParams.getString("privateKey");
        Map<String,String> signMap = new HashMap<>();
        signMap.put("tranType",object.getString("tranType"));
        signMap.put("respCode",object.getString("respCode"));
        signMap.put("respDesc",object.getString("respDesc"));
        signMap.put("merReqNo",object.getString("merReqNo"));
        signMap.put("amt",object.getString("amt"));
        signMap.put("serverRspNo",object.getString("serverRspNo"));
        signMap.put("tranTime",object.getString("tranTime"));
        String sign =getSign(signMap, privateKey);
        _log.info("加签信息：map-{},sign->{}", object, sign );
        try{
            if (sign.equals(retSign)){
                if ("0000".equals(object.get("respCode"))){
                    //查询代付订单状态
                    String queryUrl = accountParams.getString("queryUrl");
                    TreeMap<String, String> obj = new TreeMap<String, String>();
                    obj.put("tranType", "QUERY_TRANS");
                    obj.put("orderNo", transOrderId);
                    obj.put("merId", payPassageAccount.getPassageMchId());
                    String querySign = getSign(obj,privateKey);
                    obj.put("sign", querySign);
                    _log.info("查询请求url={}，param={},json->{}",queryUrl,obj,JSONObject.toJSONString(obj));
                    String respData = NewblongTransService.call(queryUrl,obj);
                    _log.info("查询结束respData->{}",respData);
                    if (StringUtils.isNotEmpty(respData)) {
                        JSONObject jsonObject = JSONObject.parseObject(respData);
                        String code = jsonObject.getString("respCode");
                        String payCode = jsonObject.getString("payCode");
                        if ("0000".equals(code) && "0000".equals(payCode)){
                            String chanelOrderNo = object.getString("serverRspNo");
                            int result =  rpcCommonService.rpcTransOrderService.updateStatus4Success(transOrderId, "");
                            _log.info("更新订单状态为支付成功: result={}", result);
                            if(result == 1){
                                // 通知业务系统
                                baseNotify4MchTrans.doNotify(payOrder, true);
                                return "success";
                            }
                        }
                    }
                }else {
                    _log.info("orderStatus error");
                }

            }else {
                _log.info("sign error");
            }
        }catch (Exception e){
            e.printStackTrace();
            _log.info("sign error,e->{}",e.getMessage());
        }
        return "fail!";
    }

    private String getSign(Map<String,String>object, String privateKey) {
        SortedMap<String,String> map = new TreeMap<>(object);
        map.remove("sign");
        // 生成签名
        StringBuffer paramstr = new StringBuffer();
        for (String pkey : map.keySet()) {
            String pvalue = map.get(pkey);
            if (pvalue != null && pvalue != "") {
                paramstr.append(pkey + "=" + pvalue + "&");
            }
        }
        String paramsrc = paramstr.substring(0, paramstr.length() - 1);
        StringBuffer strbuff = new StringBuffer();
        strbuff.append(paramsrc +  privateKey);
        String sign = null;
        try {
            sign = PayDigestUtil.md5(strbuff.toString(), "UTF-8");
            _log.info("签名:" + sign);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return sign;
    }


}
